const { ccclass, property } = cc._decorator;

/**
 * 通用节点池管理类
 */
export default class PoolManager {
    private static _instance: PoolManager = null
    private _nodePoolMap: Map<string, cc.NodePool> = new Map()

    /**
     * 单例实例
     */
    public static get instance() {
        if (!this._instance) {
            this._instance = new PoolManager()
        }
        return this._instance
    }

    /**
     * PoolManager为单例
     */
    private constructor() { }

    /**
     * 获取某个节点
     * @param prefab 节点对应的预制体 
     * @param parent 节点要被挂载的父节点
     */
    public getNode(prefab: cc.Prefab, parent?: cc.Node): cc.Node {
        // console.log('[PoolManager] getNode(), prefab=', prefab.name)
        let node: cc.Node = null
        if (this._nodePoolMap.has(prefab.name)) {
            const pool = this._nodePoolMap.get(prefab.name)
            if (pool.size() > 0) {
                node = pool.get()
            } else {
                node = cc.instantiate(prefab)
            }
        } else {
            this._nodePoolMap.set(prefab.name, new cc.NodePool())
            node = cc.instantiate(prefab)
        }

        node.name = prefab.name
        if (parent) {
            node.parent = parent
        }
        return node
    }

    /**
     * 回收节点
     * @param node 要回收的节点
     */
    public putNode(node: cc.Node): void {
        // console.log('[PoolManager] putNode(), node=', node.name)
        let pool: cc.NodePool = null

        if (!this._nodePoolMap.has(node.name)) {
            this._nodePoolMap.set(node.name, new cc.NodePool())
        }

        node.parent = null
        pool = this._nodePoolMap.get(node.name)
        pool.put(node)
    }
}
